<template>
  <div class="main">

    <div class="listTop">
      <header class="head">
        <van-icon name="arrow-left" class="reBtn" @click="reBack()" />
        <van-button type="info" class="labelBtn" size="small">
          <van-icon name="comment" style="margin-right: 3px;" />沿街</van-button>
        <van-search v-model="value" class="reSearch" :show-action="showAction" placeholder="请输入道路或商铺" @search="onSearch"
          @cancel="onCancel" @focus="onFocus" />
      </header>
    </div>
    <div id="container" class="map-container">
      <div class="breadcrumb">
        <span v-for="(item, index) in potalTiles" @click="backLevel(item)">{{ item.name }}<span style="margin:0 3px;"
            v-if="index != potalTiles.length - 1">></span></span>
      </div>
      <div class="market-label" v-if="orgLevel <= 3">市场份额</div>
      <div class="fene" v-if="orgLevel <= 3">
        <div class="fene-item">
          <i></i>
          <span>前30%</span>
        </div>
        <div class="fene-item">
          <i style="background: #FF9E00;"></i>
          <span>30%-70%</span>
        </div>
        <div class="fene-item">
          <i style="background: #FD471F;"></i>
          <span>后30%</span>
        </div>
      </div>
      <div class="fene" v-if="orgLevel > 3">
        <div style="font-size: 2.5rem;color: #000;font-weight: 600;margin-bottom: 10px;">打点类型</div>
        <div class="fene-item" style="margin-bottom: 10px;" v-for="item in dotList" :key="item">
          <img :src="item.img" style=" width: 17px;height: 21px;" />
          <span>{{ item.name }}</span>
        </div>
      </div>
      <div :class="touchFlag ? 'detailed-list-t' : 'detailed-list'">
        <div style="width: 100%;position: relative;">
          <img src="@/assets/img/line.png" @touchstart="handleTouchStart" @touchmove="handleTouchMove"
            @touchend="handleTouchEnd" class="lines" />
          <div class="area-city">
            <img src="@/assets/img/fhwg.png" style="width: 14px;height: 14px;padding-left: 10px;" />
            <span style="margin-left: 4px;font-weight: 550;"> {{ areaName }}</span>
          </div>
          <div class="qd-part">
            <div class="qd1">
              <div class="num1">19980</div>
              <div class="title1">小区个数</div>
            </div>
            <div class="qd1">
              <div class="num1">26980</div>
              <div class="title1">端口数</div>
            </div>
            <div class="qd1">
              <div class="num1">60%</div>
              <div class="title1">已覆盖</div>
            </div>
            <div class="qd1">
              <div class="num1">40%</div>
              <div class="title1">未覆盖</div>
            </div>

          </div>
          <van-dropdown-menu>
            <van-dropdown-item v-model="value2" :options="option2" />
            <van-dropdown-item v-model="value1" :options="option1" />
          </van-dropdown-menu>
          <van-list v-model="loading" v-if="touchFlag" :finished="finished" finished-text="没有更多了" @load="onLoad">
            <div v-for="item in list" :key="item">
              <div class="item_out" @click="itemClick(item)">
                <div style="display: flex; flex-direction: row">
                  <img style="align-self: center; border-radius: 5px" width="80px" height="80px"
                    src="https://img01.yzcdn.cn/vant/cat.jpeg" />

                  <div class="item_middle">
                    <div style="font-size: 3rem; margin-left: 2rem; color: black;font-weight: 550;">
                      雨城面馆家常小炒
                    </div>
                    <div style="color: #7f7f7f; font-size: 2.2rem; margin: 2rem 0 0 2rem">
                      <span class="label-l">电信</span>
                      <span style="margin: 0 6px;">未建档</span>
                      <span class="label-l">已摸排</span>
                    </div>
                    <div style="color: #7f7f7f; font-size: 2.2rem; margin: 2rem 0 0 2rem">
                      地址：哈尔滨市松北区
                    </div>
                  </div>
                </div>
              </div>
              <div class="item_divider" />
            </div>
          </van-list>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { initMap, addPolygonOverLay } from "@/utils/map"
import { mapActions } from "vuex";
import { decrypt_obj } from "@/utils/aesUtil"
import { shops } from "@/utils/shops"
import redMarker from "@/assets/img/icon1.png"
import { hebDataList } from "@/utils/heb"
import Vue from 'vue';
import { DropdownMenu, DropdownItem, Toast } from "vant";
Vue.use(Toast);
Vue.use(DropdownMenu);
Vue.use(DropdownItem);
export default {
  data() {
    return {
      value: '',
      value1: 0,
      value2: 'a',
      option1: [
        { text: '商机多优先', value: 0 },
        { text: '新款商品', value: 1 },
        { text: '活动商品', value: 2 }
      ],
      option2: [
        { text: '默认排序', value: 'a' },
        { text: '好评排序', value: 'b' },
        { text: '销量排序', value: 'c' }
      ],
      dotList: [
        { name: "已覆盖", img: require("@/assets/img/icon1.png") },
        { name: "未覆盖", img: require("@/assets/img/icon2.png") },
      ],
      areaName: "全省",
      showAction: false,
      areaList: [{ orgId: "2300", orgLevel: "1", name: "全省" }],
      map: null,
      polygon: null,
      loading: false,
      finished: false,
      year: "2023",
      orgId: "2300",
      orgLevel: "1",
      markers: [],
      touchFlag: false,
      centers: [126.532125, 45.812642],
      list: [1, 2, 3],
      dotmarkers: [],
      shopMarksList: [],
      potalTiles: [{ orgId: "2300", orgLevel: "1", name: "全省" }],
      zoom: 5,
      polygonList: null,
    };
  },

  mounted() {
    this.polygonList = new Map();
    this.initMaps();
    this.initData()
  },
  methods: {
    ...mapActions({
      getAreaGeo: "pageApi/getAreaGeo",
      pensonPanelApi: "pageApi/pensonPanelApi",
    }),
    itemClick(row) {
      this.$router.push({ name: "shopsDetail", params: { ...row, type: 'xq' } })
    },
    onLoad() {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      setTimeout(() => {
        for (let i = 0; i < 10; i++) {
          this.list.push(this.list.length + 1);
        }
        // 加载状态结束
        this.loading = false;
        // 数据全部加载完成
        if (this.list.length >= 20) {
          this.finished = true;
        }
      }, 1000);
    },
    backLevel(item) {
      this.clearMarkers()
      this.removePolygon()
      if (item.name == '全省') {
        this.potalTiles = []
        this.potalTiles.push(item)
        this.orgId = item.orgId
        this.orgLevel = item.orgLevel
      } else {
        let areaIds = this.potalTiles
        let ss = areaIds.splice(areaIds.length - 1, 1)
        let areaId1 = areaIds[areaIds.length - 1]
        this.orgId = item.orgId
        this.orgLevel = item.orgLevel
      }
      this.initData()
    },
    //地图初始化
    initMaps() {
      this.map = initMap("container", this.centers, this.zoom)
      // this.pensonPanelApi({ token: "6e6220c3b50d837002cee7c2e616e142-974ee4877c95a5b74c9640b4f8ea6168-bd2d181c582569c90668702438792dcb" }).then(res => {
      //   console.log(decrypt_obj(res.data.obj), "---")
      // })
    },
    initData() {
      if (this.orgId == 2301 && this.orgLevel == 2) {
        this.loadMapPolygon(hebDataList)
      } else {
        this.getAreaGeo({
          orgId: this.orgId,
          orgLevel: this.orgLevel,
        }).then((res) => {
          if (res.data.code == 200) {
            let data = res.data.data
            this.loadMapPolygon(data)
          } else {
            this.$toast(res.data.msg);
          }
        });
      }
    },
    loadMapPolygon(data) {
      if (this.orgLevel == 1) {
        this.zoom = 5.5
      } else if (this.orgLevel == 2) {
        this.zoom = 7
      } else {
        this.zoom = 9
      }
      if (this.orgLevel <= 3) {
        this.map.setCenter([data[0].centerLng, data[0].centerLat])
        this.map.setZoom(this.zoom)
      }
      //清除覆盖物
      this.polygonList.forEach((data, key) => {
        this.map.remove(data.polygon);
        if (data.label) {
          this.map.remove(data.label);
        }
      });
      this.polygonList = new Map();
      let polygons = [];
      data.forEach((item, i) => {
        let color = "#0077FF"
        if (i >= 0 && i < 4) {
          color = "#0077FF"
        } else if (i >= 4 && i < 8) {
          color = "#FF9C00"
        } else {
          color = "#F7440A"
        }
        if (item.coordinates.length != 0) {
          let polygon = new AMap.Polygon({
            path: item.coordinates,
            strokeColor: color,
            fillColor: color, //多边形填充颜色
            strokeWeight: 2,
            strokeOpacity: 0.65,
            fillOpacity: 0.2, //填充透明度
            cursor: "pointer",
            zIndex: 50
          });
          polygons.push(polygon);
          //区域中心点
          // let point = this.getCenterPoint(polygon.getPath());
          let point = new AMap.LngLat(item.centerLng, item.centerLat);
          let rowNum = i + 1;
          //存储当前地图信息
          let oldData = {};
          let extData = {};
          oldData.orgId = item.orgId;
          oldData.point = point;
          extData.oldData = oldData;
          polygon.setExtData(extData);
          let contentDiv = "<div class=\"map_tag\">";
          // contentDiv += "      <div class=\"maptag_num\">" + rowNum + "</div>";
          contentDiv += "      <span class=\"maptag_tit\">" + item.name + "</span><span class=\"maptag_txt\"></span>";
          contentDiv += " </div>";
          let text = new AMap.Text({
            text: "",
            anchor: 'center', // 设置文本标记锚点
            draggable: false,
            cursor: 'pointer',
            angle: 0,
            offset: [-10, -10],
            zIndex: "50",
            label: {
              direction: 'top',
              content: contentDiv,
              // offset: new AMap.Pixel(-25, -2)
            },
            position: point
          });
          text.setMap(this.map);
          text.setText("");
          text.on("mouseover", () => {
            text.setzIndex(51);
            if (this.checkCityId) {
              let oldPolyonList = this.polygonList.get(this.checkCityId);
              if (oldPolyonList != undefined) {
                let extData = oldPolyonList.polygon.getExtData();
                oldPolyonList.polygon.setOptions({
                  fillOpacity: extData.fillOpacity
                });
              }
            }
            this.checkCityId = item.orgId;
            let checkPolyonList = this.polygonList.get(this.checkCityId);
            if (checkPolyonList) {
              checkPolyonList.polygon.setOptions({
                fillOpacity: "0.8"
              });
            }
          });
          text.on("mouseout", () => {
            text.setzIndex(50);
            this.map.clearInfoWindow();
          });
          text.on("click", () => {
            let lat = point.lat;
            let lng = point.lng;
            this.showQYTip(lng, lat, item.orgId);
          });
          let morgLevel = item.orgLevel ? item.orgLevel : 4
          text.on("dblclick", () => {
            this.cityId = item.orgId;  //用户存储纸质机构Id
            this.cityName = item.name;  //用户存储纸质机构Name
            this.cityLevel = morgLevel;
            this.orgLevel = morgLevel;
            let param = { orgId: item.orgId, name: item.name, orgLevel: morgLevel }
            const index = this.potalTiles.findIndex(item => item.orgId === param.orgId);
            if (index !== -1) {
              this.$set(this.potalTiles, index, param);
            } else {
              this.potalTiles.push(param)
            }
            if (parseInt(morgLevel) < 3) {
              this.addQYOverlay(item.orgId);
            } else {
              this.addWGOverlay(item.orgId);
            }
            this.showReturnBox();
          });
          this.polygonList.set(item.orgId, {
            orgId: item.orgId,
            orgName: item.name,
            orgLevel: morgLevel,
            polygon: polygon,
            cneterPoint: point,
            label: text
          });
          console.log("level", morgLevel);
          if (parseInt(morgLevel) <= 4) { //网格层级以上可下钻
            polygon.on("click", () => {
              this.orgId = item.orgId
              this.orgLevel = morgLevel;
              let param = { orgId: item.orgId, name: item.name, orgLevel: morgLevel }
              const index = this.potalTiles.findIndex(item => item.orgId === param.orgId);
              if (index !== -1) {
                this.$set(this.potalTiles, index, param);
              } else {
                this.potalTiles.push(param)
              }
              this.initData(item.orgId);
              if (morgLevel == 4) {
                this.addMarker()
              }
            });
          }
          polygon.on("mouseover", () => {
            if (this.checkCityId) {
              let oldPolyonList = this.polygonList.get(this.checkCityId);
              if (oldPolyonList != undefined) {
                let extData = oldPolyonList.polygon.getExtData();
                oldPolyonList.polygon.setOptions({
                  fillOpacity: extData.fillOpacity
                });
              }
            }
            this.checkCityId = item.orgId;
            let checkPolyonList = this.polygonList.get(this.checkCityId);
            if (checkPolyonList != undefined) {
              checkPolyonList.polygon.setOptions({
                fillOpacity: "0.8"
              });
              checkPolyonList.label.setzIndex(51);
            }
          });
          polygon.on("mouseout", () => {
            if (this.checkCityId) {
              let oldPolyonList = this.polygonList.get(this.checkCityId);
              if (oldPolyonList != undefined) {
                var extData = oldPolyonList.polygon.getExtData();
                oldPolyonList.polygon.setOptions({
                  fillOpacity: extData.fillOpacity
                });
                if (oldPolyonList.label != undefined) {
                  oldPolyonList.label.setzIndex(50);
                }
              }
            }
          });
        }
      });
      this.map.add(polygons);
      //根据坐标值自动调节最佳视角
      // this.map.setFitView(polygons, true);
    },
    addQYOverlay(orgId) { },
    addWGOverlay(orgId) {
      if (orgId == '193960004') {

      }
    },
    showQYTip(LON, LAT, orgId) {

    },
    //清除所有的标记点
    clearMarkers() {
      if (this.shopMarksList) {
        this.shopMarksList.forEach((item, i) => {
          this.map.remove(item);
        });
      }
    },
    addMarker() {
      if (this.shopMarksList) {
        this.shopMarksList.forEach((item, i) => {
          this.map.remove(item);
        });
      }
      this.map.setZoom(15)
      this.map.setCenter([126.542247, 45.80867]);
      let position;
      let marker;
      var redIcon = new AMap.Icon({
        image: redMarker, // Icon的图像，本地图标Vue引入
        size: new AMap.Size(24, 27),  //图标所处区域大小
        imageSize: new AMap.Size(24, 27) //图标大小
      });
      let _this = this
      for (let i = 0; i < 20; i++) {
        let item = shops[i];
        position = new AMap.LngLat(item.AMAP_LNG, item.AMAP_LAT);
        marker = new AMap.Marker({
          position: position,
          icon: redIcon,
          // 以 icon 的 [center bottom] 为原点
          offset: new AMap.Pixel(-13, -30)
        });
        // 将 markers 添加到地图
        this.map.add(marker);
        this.shopMarksList.push(marker);
        marker.on('click', function () {
          _this.$router.push({ name: "shopsDetail", params: { ...item, type: 'xq' } })
        });
      }

    },
    showShopDetail() {
      alert(1)
    },
    addLabelMaker(name, point) {
      var text = new AMap.Text({
        text: name,
        anchor: 'center', // 设置文本标记锚点
        draggable: true,
        cursor: 'pointer',
        // angle:10,
        style: {
          'padding': '0.8rem 2rem',
          'margin-bottom': '1rem',
          'border-radius': '.25rem',
          'background-color': 'white',
          'border-width': 0,
          'box-shadow': '0 2px 6px 0 rgba(114, 124, 245, .5)',
          'text-align': 'center',
          'font-size': '12px',
          'color': '#000'
        },
        position: point
      });
      text.setMap(this.map);
      return text
    },
    //移除覆盖物
    removePolygon() {
      // 首先获取当前地图中所有覆盖物的实例。
      let mapPolyArr = this.map.getAllOverlays('polygon')
      // 定义一个空数组用来存放需要删除的覆盖物实例。
      let arr = []
      for (let i = 0; i < mapPolyArr.length; i++) {
        // 将需要删除的项添加到空数组里
        arr.push(mapPolyArr[i])
      }
      // 移除覆盖物
      this.map.remove(arr)
    },
    onSearch() {
      this.$toast(this.value);
    },
    onFocus() {
      this.showAction = true;
    },
    onCancel() {
      this.showAction = false;
    },
    reBack() {
      this.$router.go(-1)
    },
    handleTouchStart(event) {
      // 触摸开始时的处理逻辑
      console.log('Touch start', event);
    },
    handleTouchMove(event) {
      // 触摸移动时的处理逻辑
      console.log('Touch move', event);
    },
    handleTouchEnd(event) {
      // 触摸结束时的处理逻辑
      console.log('Touch end', event);
      this.touchFlag = !this.touchFlag
    },
    jump() {
      this.$router.push({ name: "detils", query: { edit: true } })
    },

  },
};
</script>

<style lang="scss" scoped type='text/css'>
.main {
  background-color: #f3f3f3;
  height: 100%;
}

.listTop {
  height: 10rem;
  color: #333;
  background: #fff;

  .head {
    font-size: 3.4rem;
    text-align: center;
    position: relative;
    display: flex;
    align-items: center;
    color: #333;
    font-family: "黑体";
    // padding: 3rem 0 3rem;

    .reBtn {
      position: absolute;
      left: 1.5rem;
      top: 2.5rem;
      font-size: 4.8rem;
    }

    .labelBtn {
      position: absolute;
      left: 6rem;
      top: 0.5rem;
      width: 12rem;
      top: 2rem;
    }

    .reSearch {
      position: absolute;
      left: 18rem;
      top: 0.2rem;
      width: 75%;
    }
  }
}

.map-container {
  width: 100%;
  height: calc(100% - 10rem);
  position: relative;

  .breadcrumb {
    position: absolute;
    top: 10px;
    left: 10px;
    z-index: 999;

    span {
      color: #007BFF;
      font-size: 2.5rem;
      font-weight: bold;
      cursor: pointer;
      margin-right: 5px;
    }
  }

  .market-label {
    position: absolute;
    right: 10px;
    bottom: 200px;
    z-index: 999;
    background: #fff;
    color: #000;
    width: 110px;
    padding: 5px;
    font-size: 2rem;
    text-align: center
  }

  .fene {
    position: absolute;
    right: 10px;
    bottom: 110px;
    background: #fff;
    width: 110px;
    z-index: 999;
    height: auto;
    padding: 10px;

    .fene-item {
      width: 100%;
      height: 20px;
      display: flex;
      flex-direction: row;
      align-items: center;

      i {
        width: 20px;
        height: 10px;
        display: block;
        background: #007BFF;
        margin-right: 5px;
      }

      span {
        color: #000;
        font-size: 2.5rem;
      }
    }
  }

  .lines {
    position: absolute;
    top: 0;
    left: 49%;
    z-index: 1000;
  }

  .detailed-list-t {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 80%;
    background: #fff;
    z-index: 999;
    overflow: auto;
  }

  .detailed-list {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 90px;
    background: #fff;
    z-index: 999;
    overflow: auto;
  }

  /* 开启滚动 */
  .area-city {
    font-size: 2.5rem;
    color: #007BFF;
    display: flex;
    align-items: center;
    padding: 10px;
  }

  .qd-part {
    width: 100%;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;

    .qd1 {
      width: 25%;
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;

      .num1 {
        font-size: 3.5rem;
        color: #000;
        font-weight: bold;
      }

      .title1 {
        font-size: 2.5rem;
        color: #666;
      }
    }
  }

  .item_out {
    padding: 2rem;
    background: white;
    height: 18rem;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
  }

  .item_divider {
    width: 100%;
    height: 0.2rem;
    background: #e8e8e8;
  }

  .label-l {
    background: #FFF4D7;
    padding: 4px;
    font-size: 2rem;
    color: #FFBA5B;
  }
}

.custom-content-marker {
  img {
    width: 12px;
    height: 12px;
  }
}

::v-deep .amap-marker-label {
  position: absolute;
  z-index: 2;
  border: 1px solid #e0e0e0;
  background-color: #fff;
  border-radius: 5px;
  white-space: nowrap;
  cursor: default;
  padding: 3px 6px;
  font-size: 12px;
  line-height: 14px;
}

::v-deep .amap-overlay-text-container {
  padding: 0;
}
</style>